using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model.LMZWorkSchedule;

namespace WPF_MVVM_Test.Services.LMZWorkSchedule
{
    /// <summary>
    /// 报工质检服务类
    /// </summary>
    public class WorkReportQualityService : IDisposable
    {
        private readonly HttpClient _httpClient;
        private readonly string _baseUrl = "http://8.140.242.140:8888/api/LMZWorkSchedule";

        public WorkReportQualityService()
        {
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 获取报工质检分页数据
        /// </summary>
        /// <param name="queryParams">查询参数</param>
        /// <returns>分页数据</returns>
        public async Task<WorkReportQualityPagedData> GetWorkReportQualityPagedAsync(WorkReportQualityQueryParams queryParams)
        {
            try
            {
                // 构建查询URL
                var url = $"{_baseUrl}/basic-list?pageIndex={queryParams.PageIndex}&pageSize={queryParams.PageSize}";
                
                if (!string.IsNullOrEmpty(queryParams.OrderName))
                {
                    url += $"&orderName={Uri.EscapeDataString(queryParams.OrderName)}";
                }
                
                if (!string.IsNullOrEmpty(queryParams.Status))
                {
                    url += $"&status={Uri.EscapeDataString(queryParams.Status)}";
                }

                var response = await _httpClient.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var jsonContent = await response.Content.ReadAsStringAsync();
                var options = new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                };

                var apiResponse = JsonSerializer.Deserialize<WorkReportQualityApiResponse>(jsonContent, options);
                
                return apiResponse?.Data ?? new WorkReportQualityPagedData();
            }
            catch (Exception ex)
            {
                // 这里可以添加日志记录
                Console.WriteLine($"获取报工质检数据失败: {ex.Message}");
                return new WorkReportQualityPagedData();
            }
        }

        /// <summary>
        /// 获取报工质检数据（简化版本，用于快速调用）
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页大小</param>
        /// <param name="orderNameFilter">工单名称过滤</param>
        /// <param name="statusFilter">状态过滤</param>
        /// <returns>元组：(数据列表, 总数量, 总页数)</returns>
        public async Task<(List<WorkReportQualityItem> items, int totalCount, int totalPage)> GetWorkReportQualityAsync(
            int pageIndex, int pageSize, string orderNameFilter = "", string statusFilter = "")
        {
            var queryParams = new WorkReportQualityQueryParams
            {
                PageIndex = pageIndex,
                PageSize = pageSize,
                OrderName = orderNameFilter,
                Status = statusFilter
            };

            var result = await GetWorkReportQualityPagedAsync(queryParams);
            return (result.Data, result.TotalCount, result.TotalPage);
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}